using FileTransferDesktop.Services;
using Wpf.Ui;
using Wpf.Ui.Controls;

namespace FileTransferDesktop.ViewModels.Controls;

public partial class UserMenuControlViewModel : ObservableObject
{
    private readonly IAuthenticationService _authenticationService;
    private readonly ISnackbarService _snackbarService;

    [ObservableProperty]
    private bool _isLoggedIn = false;

    [ObservableProperty]
    private string _userName = string.Empty;

    [ObservableProperty]
    private string _userEmail = string.Empty;

    [ObservableProperty]
    private string _userDisplayName = string.Empty;

    [ObservableProperty]
    private string _avatarUrl = string.Empty;

    [ObservableProperty]
    private string _greetingText = "Hello";

    public UserMenuControlViewModel(
        IAuthenticationService authenticationService,
        ISnackbarService snackbarService
    )
    {
        _authenticationService = authenticationService;
        _snackbarService = snackbarService;

        // 订阅认证状态变化事件
        _authenticationService.AuthenticationStatusChanged += OnAuthenticationStatusChanged;

        // 初始化当前状态
        UpdateAuthenticationStatus();
    }

    private void OnAuthenticationStatusChanged(object? sender, bool isAuthenticated)
    {
        // 在UI线程上更新属性
        Application.Current.Dispatcher.Invoke(() =>
        {
            UpdateAuthenticationStatus();
        });
    }

    private void UpdateAuthenticationStatus()
    {
        IsLoggedIn = _authenticationService.IsAuthenticated;

        if (IsLoggedIn && _authenticationService.CurrentUser != null)
        {
            var user = _authenticationService.CurrentUser;
            UserName = user.Username ?? string.Empty;
            UserEmail = user.Email ?? string.Empty;
            UserDisplayName = user.DisplayName ?? string.Empty;
            AvatarUrl = user.AvatarUrl ?? string.Empty;

            // 设置问候语，优先显示DisplayName，其次Username
            GreetingText =
                !string.IsNullOrEmpty(UserDisplayName) ? $"Hello, {UserDisplayName}"
                : !string.IsNullOrEmpty(UserName) ? $"Hello, {UserName}"
                : "Hello";
        }
        else
        {
            // 未登录状态
            UserName = string.Empty;
            UserEmail = string.Empty;
            UserDisplayName = string.Empty;
            AvatarUrl = string.Empty;
            GreetingText = "Hello";
        }
    }

    [RelayCommand]
    private async Task LogoutAsync()
    {
        try
        {
            await _authenticationService.LogoutAsync();

            // 显示登出成功通知
            _snackbarService.Show(
                "登出成功",
                "您已成功登出",
                ControlAppearance.Info,
                new SymbolIcon(SymbolRegular.SignOut24),
                TimeSpan.FromSeconds(3)
            );
        }
        catch (Exception ex)
        {
            // 显示错误通知
            _snackbarService.Show(
                "登出失败",
                $"登出时发生错误：{ex.Message}",
                ControlAppearance.Danger,
                new SymbolIcon(SymbolRegular.ErrorCircle24),
                TimeSpan.FromSeconds(5)
            );
        }
    }

    [RelayCommand]
    private void NavigateToUserProfile()
    {
        if (Application.Current.MainWindow is INavigationWindow navWindow)
        {
            navWindow.Navigate(typeof(FileTransferDesktop.Views.Pages.UserProfilePage));
        }
    }

    [RelayCommand]
    private void NavigateToManagement()
    {
        if (Application.Current.MainWindow is INavigationWindow navWindow)
        {
            navWindow.Navigate(typeof(FileTransferDesktop.Views.Pages.ManagementPage));
        }
    }

    [RelayCommand]
    private void NavigateToSettings()
    {
        if (Application.Current.MainWindow is INavigationWindow navWindow)
        {
            navWindow.Navigate(typeof(FileTransferDesktop.Views.Pages.SettingsPage));
        }
    }

    // 析构函数，取消事件订阅
    ~UserMenuControlViewModel()
    {
        if (_authenticationService != null)
        {
            _authenticationService.AuthenticationStatusChanged -= OnAuthenticationStatusChanged;
        }
    }
}
